package com.spm.librarianmanagersystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spm.librarianmanagersystem.mapper.BookMapper;
import com.spm.librarianmanagersystem.mapper.MemberMapper;
import com.spm.librarianmanagersystem.mapper.ReservationMapper;
import com.spm.librarianmanagersystem.pojo.Book;
import com.spm.librarianmanagersystem.pojo.Reservation;
import com.spm.librarianmanagersystem.service.SendEmail;
import com.spm.librarianmanagersystem.utils.ContextUtil;
import com.spm.librarianmanagersystem.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SendEmailImpl implements SendEmail {
    /**
     * @param receiver
     */

    @Autowired
    ReservationMapper reservationMapper;
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    BookMapper bookMapper;

    @Override
    public void sendAuthCodeEmail(String receiver, Reservation reservation) throws Exception {

        try {
            EmailUtil.sendEmail(receiver, "预定取消提醒消息", ContextUtil.getHtmlAuthMessage(receiver, (JSONObject) JSON.toJSON(reservation)), "html");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("邮件发送异常");
        }

    }

    @Override
    public void sendEmailReservRemind(String ISBN) throws Exception {
        List<String> reservMemberID = reservationMapper.getReservingMembers(ISBN);
        Book book = bookMapper.getABook(ISBN);
        for (String id : reservMemberID) {
            String receiver_mail = memberMapper.getEmailByID(id);
            try {
                EmailUtil.sendEmail(receiver_mail, "预定取消提醒消息", ContextUtil.getHtmlAuthMessageReservRemind(receiver_mail, (JSONObject) JSON.toJSON(book)), "html");
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("邮件发送异常");
            }
        }
    }

}
